import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:hairen_app/pages/plug/func.dart';
import './register.dart';
import 'package:hairen_app/server/server.dart';
import 'package:hairen_app/server/saveInfo.dart';
import 'dart:async';

import 'package:hairen_app/main.dart';
import 'package:hairen_app/server/state/UserInfoModel.dart';

class Login extends StatefulWidget {
  final Widget design;

  Login({this.design}) : super();

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _LoginState();
  }
}

class _LoginState extends State<Login> {
  TextEditingController _usernameCpntroller = new TextEditingController();
  TextEditingController _passwordCpntroller = new TextEditingController();
  bool isSubmit = true;
  bool isLogin = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  String token = "";
  Map userInfo = {};

  @override
  Widget build(BuildContext context) {
//    saveCache();

    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        title: new Text("登陆"),
      ),
      body: Align(
        alignment: Alignment.center,
        child: new Container(
          padding:
              EdgeInsets.only(left: 25.0, right: 25.0, top: 10.0, bottom: 10.0),
          color: Theme.of(context).backgroundColor,
          child: new Form(
            child: new Column(
              children: <Widget>[
                new SizedBox(
                  height: 30.0,
                ),
                new Image.asset(
                  'assets/logo.png',
                  width: 80.0,
                ),
                new SizedBox(height: 20.0),
                new Container(
                  padding: EdgeInsets.only(left: 10.0, right: 10.0),
                  color: Colors.white,
                  child: new TextField(
                    controller: _usernameCpntroller,
                    decoration: new InputDecoration(
                      icon: new Icon(
                        Icons.perm_identity,
                        color: Theme.of(context).backgroundColor,
                      ),
                      border: InputBorder.none,
                      hintText: "请输入用户名",
                    ),
                    maxLines: 1,
//                       maxLength: 30,
                  ),
                ),
                new SizedBox(
                  height: 20.0,
                ),
                new Container(
                  padding: EdgeInsets.only(left: 10.0, right: 10.0),
                  color: Colors.white,
                  child: new TextField(
                    controller: _passwordCpntroller,
                    decoration: new InputDecoration(
                      icon: new Icon(
                        Icons.lock_outline,
                        color: Theme.of(context).backgroundColor,
                      ),
                      border: InputBorder.none,
                      hintText: "请输入密码",
                    ),
                    obscureText: true,
                    maxLines: 1,
//                       maxLength: 30,
                  ),
                ),
                new SizedBox(
                  height: 20.0,
                ),
                new Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new Expanded(
                      flex: 1,
                      child: new FlatButton(
                          onPressed: () {
                            Navigator.of(context).push(new CupertinoPageRoute(
                                builder: (context) => new Register()));
                          },
                          child: new Text(
                            '注册账号',
                            style: TextStyle(color: Colors.white),
                          )),
                    ),
                    new Expanded(
                      flex: 1,
                      child: new Builder(builder: (BuildContext context) {
                        return new FlatButton(
                            color: Colors.white,
                            onPressed: () {
                              if (isSubmit) {
                                setState(() {
                                  isSubmit = false;
                                });
                                String username =
                                    _usernameCpntroller.text.trim();
                                String password =
                                    _passwordCpntroller.text.trim();
                                if (username == "") {
                                  func.MySnackBar(context, '用户名不能为空',
                                      color: Colors.red);
                                  setState(() {
                                    isSubmit = true;
                                  });
                                } else if (password == "") {
                                  func.MySnackBar(context, '密码不能为空',
                                      color: Colors.red);
                                  setState(() {
                                    isSubmit = true;
                                  });
                                } else {
                                  Server.login(data: {
                                    "username": username,
                                    "password": password
                                  }).then((ret) {
                                    setState(() {
                                      isSubmit = true;
                                    });
                                    if (ret['code'] == 0) {
                                      func.MySnackBar(context, ret['msg'],
                                          color: Colors.red);
                                    } else {
                                      //报错token
                                      SaveInfo.SaveToken(ret['data']['token'])
                                          .then((state) {
                                        if (state) {
                                          SaveInfo.SaveUserInfo(
                                                  ret['data']['user'])
                                              .then((state) {
                                            UserInfoModel.isLogin=true;
                                            func.MySnackBar(context, "登陆成功",
                                                color: Colors.white);
                                            Timer.periodic(Duration(seconds: 1), (r) {
                                              if(widget.design==null){
//                                                Navigator.of(context).push( new CupertinoPageRoute(  builder: (context) =>  new MyHomePage( currentIndex: 2),),);
                                                Navigator.of(context).pushAndRemoveUntil(
                                                    new MaterialPageRoute(builder: (context) => new MyHomePage( currentIndex: 2)
                                                    ), (route) => route == null);
                                              }else{
//                                                Navigator.of(context).push( new CupertinoPageRoute(  builder: (context) =>  widget.design));
                                                Navigator.of(context).pushAndRemoveUntil(
                                                    new MaterialPageRoute(builder: (context) => widget.design
                                                    ), (route) => route == null);
                                              }
                                              r.cancel();
                                            });
                                          });
                                        } else {
                                          func.MySnackBar(context, '登陆失败',
                                              color: Colors.red);
                                        }
                                      });
                                    }
                                  });
                                }
                              }
                            },
                            child: new Text('登陆',
                                style: TextStyle(
                                    color: Theme.of(context).backgroundColor)));
                      }),
                    )
                  ],
                )
              ],
            ),
          ),
        ),
      ),
      resizeToAvoidBottomPadding: false, //输入框抵住键盘
    );
  }
}
